import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class server extends WindowAdapter
implements ActionListener{
	ServerSocket server;
	Socket client;
	boolean flag;
	BufferedReader cin;
	PrintWriter cout;
	Frame f;
	Button b1;
	TextArea ta;
	TextField tf;
	public server() {
		try{
			server = new ServerSocket(1234);
			this.ChatFram("server port:"+server.getLocalPort());
			flag = true;
			while(flag) {
				client = server.accept();
				System.out.println("已经建立连接");
				InputStream is = client.getInputStream();
				cin = new BufferedReader(new InputStreamReader(is));
				OutputStream os = client.getOutputStream();
				cout = new PrintWriter(os, true);
				String aline;
				while((aline=cin.readLine()) != null) {
					ta.append(aline+"\n");
					if(aline.equals("bye")) {
						flag = false;
						break;
					}
				}
			is.close();
			cin.close();
			os.close();
			cout.close();
			client.close();
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
	public void ChatFram(String str) {
		f = new Frame("Server"+str);
		f.setSize(400,300);
		ta = new TextArea();
		f.add(ta);
		ta.setEditable(false);
		Panel p = new Panel();
		f.add(p, "South");
		tf = new TextField(20);
		b1= new Button("Send");
		p.add(tf);
		p.add(b1);
		b1.addActionListener(this);
		tf.addActionListener(this);
		f.setVisible(true);
		f.addWindowListener(this);
	}
	public void actionPerformed(ActionEvent e) {
		ta.append(tf.getText()+"\n");
		cout.println(tf.getText());
		tf.setText("");
	}
	public void windowClosing(WindowEvent e) {
		cout.println("bye");
		System.exit(0);
	}
	public static void main(String args[]) {
		new server();
	}
}
